from django.shortcuts import render, get_list_or_404, redirect
from django.http import HttpResponse, HttpResponseRedirect
import random
from django.core.cache import cache
from django.core.mail import send_mail
from django.urls import reverse

from App_SearchNovel.Tools import ParseBook
from App_SearchNovel.models import Books
from App_User_SigninAndRegister.models import User
from django.contrib.auth.hashers import make_password,check_password
from django.http import JsonResponse
# Create your views here.
def Getcode(request):
    #随机生成验证码
    yzm =str(random.randint(100, 999))
    email = request.POST.get("email")
    #django自带的缓存产品
    cache.set(email,yzm,timeout=60)
    send_mail(
        'NiceNovel邮箱验证码',
        "感谢您对本网站的支持，此次您的登录或注册的验证码："+yzm,
        '1142416566@qq.com',
        [email],
        fail_silently=False,
    )
    mes = "发送成功"
    return JsonResponse({"mes":mes})


def Register(request):
    password = request.POST.get("password")
    email = request.POST.get("email")
    emailyzm = cache.get(email)
    yzm = request.POST.get("yzm")
#起初写的是 is 而不是== 所以一直判断为false ==是比较值，is是比较地址，这一点比java好用
    if emailyzm is not None:
        if emailyzm == yzm:
            p = make_password(password)
            s = User(password=p, email=email)
            s.save()
        return render(request,"signin.html")

def Signin(request):

    email = request.POST.get("email")
    password = request.POST.get("password")
    emailyzm = cache.get(email)
    user = User.objects.get(email=email)
    if emailyzm is not None:
        if (check_password(password, user.password)):
            request.session["islogin"] = True
            request.session["userid"] = user.userid
            print(user.vipstatus)
            request.session["vipstatus"] = user.vipstatus
            try:
                nextpath = request.POST.get("next",False)
                return HttpResponseRedirect(nextpath)
            except:
                return redirect(reverse("home"))
        else:
            return HttpResponse("no")
def FormSign(request):
    return render(request, "signin.html")

def FormRegister(request):
    return render(request, "register.html")




